#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

using namespace std;

#define BUFFER_SIZE 1024

class ThreadData
{
public:
    ThreadData(struct sockaddr_in server, int sock) : _server(server), _sock(sock) {}
    struct sockaddr_in _server;
    int _sock;
};

void *send(void *args) // 发送线程
{
    ThreadData *td = (ThreadData *)args; // 获取到服务器信息和sock
    string message;                      // 发送缓冲区
    while (true)
    {
        cerr << "请输入信息:";
        getline(cin, message);
        // 首次sendto，系统会自动绑定ip和端口给该客户端
        sendto(td->_sock, message.c_str(), message.size(), 0, (struct sockaddr *)&td->_server, sizeof(td->_server));
    }
}

void *recv(void *args) // 获取到服务器信息和sock
{
    ThreadData *td = (ThreadData *)args;
    char buffer[BUFFER_SIZE]; // 接收缓冲区
    while (true)
    {
        buffer[0] = 0; // 清空

        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(td->_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
            buffer[s] = 0;
        cout << buffer << endl;
    }
}

void Usage(const char *proc)
{
    cout << "Usage: " << proc << " Server_ip Server_port" << endl;
}

//./client 127.0.0.1 8080
int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    // 1.客户端也要创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);

    // 2.客户端一般不会绑定固定端口号
    // a.手动绑定：客户只是普通人，并不知道ip和port    ×
    // b.代码绑定：万一这个端口号被别的进程用了，客户端就无法使用    ×
    // c.系统自动绑定    √

    // 定义接收方
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(atoi(argv[2]));

    // 3.发送线程和接收线程
    pthread_t send_thread, recv_thread;

    ThreadData td(server, sock);
    pthread_create(&send_thread, NULL, send, (void *)&td);
    pthread_create(&recv_thread, NULL, recv, (void *)&td); // 启动收发线程

    pthread_join(send_thread, NULL);
    pthread_join(recv_thread, NULL); // 等待线程退出

    return 0;
}